package com.example.timecodecalc;



import java.util.ListIterator;
import java.util.concurrent.CopyOnWriteArrayList;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.os.Bundle;
import android.os.Handler;
import android.text.Layout;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.StyleSpan;
import android.util.TypedValue;
import android.view.ContextThemeWrapper;
import android.view.DragEvent;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewParent;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener,OnLongClickListener,OnTouchListener {
	boolean sw_bs;
	final boolean TIMECODE_ON = true;
	Timecodes curtm;
	int indec,outdec,resprev,result,selspin;
	String customformat;
	// Начальный таймкод в фреймах 0
	int resframes;
	String tms;
	View np;
	MainActivity maincl;
	LayoutInflater infl;
	FrameLayout fl;
	LinearLayout lv;
	SharedPreferences sPref;
	LayoutParams defaulparams;
	TextView res,TIn,TOut,sign;
	Button btn,btns;
	Handler h;
	boolean FlagLongIn=false;
	boolean FlagLongOut=false;
	boolean EditCustomPad=false;
	boolean l,r,t,b;
	boolean bsel,cornerdrag;
	float xff,yff,xsf,ysf,maxr;
	float xsfb,ysfb;
	int dxsize,dysize,bwidth,bheight;
	float bweight;
	int weight;
	
	int bt[] = {R.id.digit0 ,R.id.digit1,R.id.digit2,R.id.digit3,R.id.digit4,R.id.digit5,R.id.digit6,R.id.digit7,R.id.digit8,R.id.digit9};
//	 static String[] data = {"one", "two", "three", "four", "five"};
	 Object  ndrag;
	 CopyOnWriteArrayList list;
	 ListIterator it;
	 Object currentv=null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		list = new CopyOnWriteArrayList();
		ListIterator it = list.listIterator();
		h=new Handler();
		l=r=t=b=false;
		bsel=false;
		// В главном окне  ищем ID фрейма для загрузки клавиатуры
		fl = (FrameLayout) findViewById(R.id.key_board_container);
		lv= (LinearLayout) findViewById(R.id.listbutton);
		maincl=this;
		// В главном окне ищем ID переключателя вида клавиатуры
		Switch sw = (Switch)findViewById(R.id.switch_calculator_style);
		// Читаем текущие настройки типа загружаемой клавиатуры
		sPref = getPreferences(MODE_PRIVATE);
		sw_bs = sPref.getBoolean("type calculator", !TIMECODE_ON);
		selspin = sPref.getInt("TimecodeNum", 0);
		customformat=sPref.getString("TimecodeCustom", "");
		
		String [] timecodeset = getResources().getStringArray(R.array.TimecodeFormat);
		if(customformat.length()!=0)
			timecodeset[timecodeset.length-1]=customformat;
		String [] timecodeformat= timecodeset[selspin].split(",");
		String [] tmf=timecodeformat[0].split(":");
		
			
		//  В главном окне ищем ID результата таймкода
		res = (TextView) findViewById(R.id.textresult);
		TIn = (TextView) findViewById(R.id.textViewIn);
		TOut = (TextView) findViewById(R.id.textViewOut);
		sign = (TextView) findViewById(R.id.sign);
		// Устанавливаем начальный таймкод и заполняем результат
		// resframes=66959397;
		 //resframes=0;
		result=0;
		infl= getLayoutInflater();
		
		sw.setChecked(sw_bs);
		
		if(sw_bs)
			// Загружаем клавиатуру для таймкода
		{
			np = infl.inflate(R.layout.time_code_pad, fl, true);
			
		}
		else
		{
			// Загружаем обыкновенную клавитуру
			np = infl.inflate(R.layout.simple_pad, fl, true);
			
		}
		
		fl.setOnDragListener(new ButtonDragListener());
		lv.setOnDragListener(new ButtonDragListener());
	
		
		// Активируем обработчик для переключения вида калькулятора
		sw.setOnClickListener(this);
		
		// Активируем обработчики для клавиш от 0 до 9
		for(int i=0;i<=9;i++)
			if(fl.findViewById(bt[i])==null)
			{
				Toast.makeText(this, "error created Button "+ i, Toast.LENGTH_LONG).show();
			}
		else 
		{
			findViewById(bt[i]).setOnClickListener(this);
			findViewById(bt[i]).setOnLongClickListener(this);
			findViewById(bt[i]).setOnTouchListener(this);
			   
		//	Toast.makeText(this, "Button created", Toast.LENGTH_LONG).show();
		}
		// // Активируем обработчики для клавиш от del и Clear
		findViewById(R.id.clear).setOnClickListener(this);
		findViewById(R.id.del).setOnClickListener(this);
		findViewById(R.id.equal).setOnClickListener(this);
		findViewById(R.id.plus).setOnClickListener(this);
		findViewById(R.id.minus).setOnClickListener(this);
		findViewById(R.id.clear).setOnLongClickListener(this);
		findViewById(R.id.del).setOnLongClickListener(this);
		findViewById(R.id.equal).setOnLongClickListener(this);
		findViewById(R.id.plus).setOnLongClickListener(this);
		findViewById(R.id.minus).setOnLongClickListener(this);
		findViewById(R.id.dot).setOnLongClickListener(this);
		if(sw_bs)
		{
		findViewById(R.id.In).setOnLongClickListener(this);
		findViewById(R.id.In).setOnClickListener(this);
		findViewById(R.id.Out).setOnLongClickListener(this);
		findViewById(R.id.Out).setOnClickListener(this);
		}
		findViewById(R.id.clear).setOnLongClickListener(this);
		defaulparams=((Button)findViewById(R.id.digit1)).getLayoutParams();
		
		
		curtm= new Timecodes(); // Создаем главный объект
		
		if(curtm!=null)
		{
		
		
		// Шаблон задает максимальные значения, дальше устанавливаются
		// значения разрядов таймкода
		//curtm.Creates(9999,12,31,24,60,60,25).setDigit(0,0,0,0,0,0,0).prn();// Заполняем максимальными значениями и получаем ссылку на верхний класс
		//curtm.Creates(9999).setDigit(0).prn();
		curtm.Creates(tmf).prn();
		result=curtm.TimecodeToFrames(curtm.strtime); // Сохраняем начальный таймкод ввиде фреймов
		ViewTimecode(result);
		
		// 2345:11:30:23:34:59:24
	}
		
	}
	public void correctWidth(TextView textView, int desiredWidth)
	{
	    Paint paint = new Paint();
	    Rect bounds = new Rect();

	    paint.setTypeface(textView.getTypeface());
	    float textSize = textView.getTextSize();
	    paint.setTextSize(textSize);
	    String text = textView.getText().toString();
	    paint.getTextBounds(text, 0, text.length(), bounds);

	    while (bounds.width() > desiredWidth)
	    {
	        textSize--;
	        paint.setTextSize(textSize);
	        paint.getTextBounds(text, 0, text.length(), bounds);
	    }

	    textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		final EditText edtTimecode;
		
		
		int id = item.getItemId();
		if (id == R.id.action_settings)
		{
		
			AlertDialog dialog = TimecodeDialogs.getDialog(this, TimecodeDialogs.IDD_SETTINGS);//DialogScreen.getDialog(this, DialogScreen.IDD_SETTINGS);
			 dialog.show();
			  // получаем массив для неизменяемых пресетов из файла ресурсов
			 // Создаем массив строк для формата, комментария под таймкодом и списка.
				final String [] timecodesettings = getResources().getStringArray(R.array.TimecodeFormat);
				if(customformat.length()!=0)
				{
					timecodesettings[timecodesettings.length-1]=customformat;
				}
			 	final String timecodearray[][] = new String [3][timecodesettings.length];
				String tmp[]= new String [3];
			 // Разбиваем на отдельные массивы из строки по запятым и заполняем массив
				 
				for(int i=0;i<timecodesettings.length;i++)
			    {
			    	tmp=timecodesettings[i].split(",",3);
			    	timecodearray[0][i]=(tmp.length>0)?tmp[0]:"24:60:60";
			    	timecodearray[1][i]=(tmp.length>1)?tmp[1]:"hh:mm:ss";
			    	timecodearray[2][i]=(tmp.length>2)?tmp[2]:"Custom Format";
			     }
				
				
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, timecodearray[2]);
	            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	            Spinner spinner = (Spinner) dialog.findViewById(R.id.spinner1);
	            Button bSave = (Button) dialog.findViewById(R.id.bSavePrefTimecode);
	            
	             spinner.setAdapter(adapter);
	            // заголовок
	            spinner.setPrompt("Title");
	            // выделяем элемент 
	            spinner.setSelection(selspin);
	           // dialog.findViewById(R.id.bSavePrefTimecode).setOnKeyListener(this);
	            edtTimecode = (EditText) dialog.findViewById(R.id.editText1);
	            if(edtTimecode!=null)
	            {
	            	edtTimecode.setText(timecodesettings[0]);
	            	if(spinner.getSelectedItemPosition()<(timecodesettings.length-1))
	            	edtTimecode.setEnabled(false);
	            	else
	            	edtTimecode.setEnabled(true);
	            		
	            }
	            
	            spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
	                @Override
	                public void onItemSelected(AdapterView<?> parent, View view,
	                    int position, long id) {
	                  // показываем позиция нажатого элемента
	                	if(edtTimecode!=null)
	    	            {
	    	            	//edtTimecode.setHint(timecodesettings[position]);
	    	            	if(position<(timecodesettings.length-1))
	    	            		    	            	edtTimecode.setEnabled(false);
	    	            	else
	    	            								edtTimecode.setEnabled(true);
	    	            	
	    	            	edtTimecode.setText(timecodesettings[position]);
	    	            	selspin=position;
	    	            
	    	            }
	                  Toast.makeText(getBaseContext(), "Position = " + position, Toast.LENGTH_SHORT).show();
	                }
	                @Override
	                public void onNothingSelected(AdapterView<?> arg0) {}       });
	            // Пробуем применить пользовательский вид таймкода
	            bSave.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                    	
                    	String tmp[],a[];
                    	// curtm.Clean();
                    	curtm=null;
                    	curtm= new Timecodes();
                    	if(selspin==(timecodesettings.length-1) && edtTimecode!=null)
                    	{
                    		tmp=edtTimecode.getText().toString().split(",");
                    		a=tmp[0].split(":");
                    	}
                    	else
                    		a=timecodearray[0][selspin].split(":");
                    		
                      	
    // Если при создании не возникло ошибок сохраняем номер выбранного пресета и работаем с выбранным
                      	if(curtm.Creates(a)==null)
                      	{
                      		Toast.makeText(getBaseContext(), getResources().getString(R.string.errtimecode), Toast.LENGTH_SHORT).show();
                      		//curtm.Creates(24,60,60,24).prn();
                      	}
                      		else
                      	{
                      		Toast.makeText(getBaseContext(),getResources().getString(R.string.truetimecode) , Toast.LENGTH_SHORT).show();
                    		Editor ed = sPref.edit();
            				ed.putInt("TimecodeNum", selspin);
            				if(selspin==(timecodesettings.length-1) && edtTimecode!=null)
            					ed.putString("TimecodeCustom",edtTimecode.getText().toString());
            					
            				ed.commit();
            				Intent intent = getIntent();
            				finish();
            				startActivity(intent);
                      	}
                       	
                    }
                });
			return true;
	     }
		if (id == R.id.custompad)
		{
			EditCustomPad=!EditCustomPad;
		/*	if(!EditCustomPad && lv.getChildCount()!=0)
			{
				lv.removeAllViews();
			}*/
			if(lv!=null && EditCustomPad)
			{
		    String [] commandsend = getResources().getStringArray(R.array.CommandSend);
		    ContextThemeWrapper newContext = new ContextThemeWrapper(this, R.style.button_simple_digit_key_style_border);
		      
		    for(int i=0;i<commandsend.length;i++)
		    {
		    	btns=new Button(newContext);
		    	btns.setText(commandsend[i]);
		    	btns.setOnLongClickListener(this);
		    	btns.setOnTouchListener(this);
				btns.setTag("command");
		    	btns.setLayoutParams(defaulparams);
		        SetLayer(btns,R.drawable.btn_keyboard_key_pressed_border,R.id.lred,0,R.id.rred,0,R.id.tred,0,R.id.bred,0);
		     	lv.addView(btns); 
		    }
		    
		    FrameLayout fllv=new FrameLayout(newContext);
		    fllv.setMinimumWidth(btns.getWidth());
		    fllv.setMinimumHeight(btns.getHeight());
		    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)btns.getLayoutParams();
		    fllv.setLayoutParams(params);
			lv.addView(fllv); 
		   
		    LinearLayout llv=new LinearLayout(newContext);
		    llv.setLayoutDirection(View.LAYOUT_DIRECTION_LTR);
		    SetLayer(llv,R.drawable.linearl_v,R.id.lred,0,R.id.rred,0,R.id.tred,0,R.id.bred,0);
			 
		    llv.setOnLongClickListener(this);
		    llv.setOnTouchListener(this);
		    fllv.addView(llv);
		   
		    FrameLayout fllh=new FrameLayout(newContext);
		    fllh.setLayoutParams(params);
		    lv.addView(fllh); 
	
		    LinearLayout llh=new LinearLayout(newContext);
		    llh.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
		    SetLayer(llh,R.drawable.linearl_h,R.id.lred,0,R.id.rred,0,R.id.tred,0,R.id.bred,0);
		    llh.setOnLongClickListener(this);
		    llh.setOnTouchListener(this);
			fllh.addView(llh);
		    
		    FrameLayout flfl=new FrameLayout(newContext);
		    flfl.setLayoutParams(params);
		    lv.addView(flfl); 
		    
		    FrameLayout fl=new FrameLayout(newContext);
		    SetLayer(fl,R.drawable.framel,R.id.lred,0,R.id.rred,0,R.id.tred,0,R.id.bred);
		    fl.setOnLongClickListener(this);
		    fl.setOnTouchListener(this);
			 
		    flfl.addView(fl);
		   
		    FrameLayout flrl=new FrameLayout(newContext);
		    flrl.setLayoutParams(params);
		    lv.addView(flrl); 
		    RelativeLayout rl=new RelativeLayout(newContext);
		    SetLayer(rl,R.drawable.relativel,R.id.lred,0,R.id.rred,0,R.id.tred,0,R.id.bred);
		    rl.setOnLongClickListener(this);
		    rl.setOnTouchListener(this);
			flfl.addView(rl);
			}
			
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public void onClick(View v) {
		//Intent intent = new Intent(this, MainActivity.class);
		Intent intent = getIntent();
		int key = v.getId();
		String temp="";
        String checkchar;
		// TODO Auto-generated method stub
		// Проверяем нажатую цифровую кнопку
        for(int i=0;i<=9;i++)
			 if(key==bt[i])
			 {
	        checkchar=String.valueOf(i);
	        curtm.check=true;
	        temp=curtm.strtime;
	        // Если первый знак не ноль добавляем с текущей позиции иначе ничего не меняем 
	        if(temp.substring(0,1).compareTo("0")==0 || curtm.positions>0) 
	        		temp=curtm.AddPosition(curtm.strtime, checkchar,curtm.positions);
	       
	         // Добавляем символ, если ошибка то значение таймкода не изменяется
	        curtm.TimecodeToFrames(temp);
	        if(curtm.check!=true)
	         	curtm.AddZero(temp, checkchar); // Добавляем ноль справа до тех пор пока таймкод не станет правильным
	        else
	        	if(curtm.positions>=1)
	        		curtm.positions--;
	        result=curtm.TimecodeToFrames(curtm.strtime);
	    	ViewTimecode(result);
			break;
			 }
		switch(key)
		{
				//
			case R.id.switch_calculator_style:	
				// Сохраняем новый вид калькулятора и загружаем с новыми настройками
				sw_bs=!sw_bs;
				Editor ed = sPref.edit();
				ed.putBoolean("type calculator", sw_bs);
				ed.commit();
				finish();
				startActivity(intent);
				break;
			case R.id.clear:
				// Очищаем текущий таймкод
				sign.setText("");
				result=0;
				ViewTimecode(result);
				break;
			case R.id.del:
				temp=curtm.strtime;
				do {temp=curtm.AddLeft(temp,"0");}
				while(curtm.check==false && curtm.positions<curtm.maxdigits);
// Добавляем ноль слева до тех пор пока таймкод не станет правильным
				curtm.end.prntwodot(curtm.end,curtm.positions); // Печатаем через двоеточие
				result=curtm.TimecodeToFrames(curtm.strtime);
				ViewTimecode(result);
					 break;
			case R.id.plus:
				sign.setText("+");
				resprev=result;
				result=0;
				ViewTimecode(result);
				
				break;
			case R.id.minus:
				sign.setText("-");
				resprev=result;
				result=0;
				ViewTimecode(result);
				
				break;
			case R.id.In:
				result=indec;
				ViewTimecode(result);
				break;
			case R.id.Out:
				result=outdec;
				ViewTimecode(result);
				break;
			case R.id.equal:
				switch(sign.getText().toString().charAt(0))
				{
				case '+':
				result=resprev+result;
				sign.setText("");
				break;
				case '-':
				result=(resprev-result)>0?(resprev-result):(result-resprev);
				sign.setText("");
				break;
				}
				ViewTimecode(result);
				break;
			
				
		}
		
	}
	public void ViewTimecode(int restime)
	{
		curtm.strtime="";
		curtm.FramesToTimecode(restime);
		curtm.end.prntwodot(curtm.end,curtm.positions);
     	res.setText(Timecode2Dot(curtm.str,curtm.strtime,curtm.positions));			//
     	//correctWidth(res,500);// Подгоняем размер текста под размеры экрана
	}
// Выделяем жирным текст заполненный нулями справа чтобы видет положение курсора	
	public Spannable Timecode2Dot(String tm2dot,String tm,int pos) // Перевод строки таймкода без двоеточия в строку таймкода с двоеточием
	{
		
		//	Toast.makeText(this, "Timecode string = " + tm, Toast.LENGTH_LONG).show();
		Spannable text = new SpannableString(tm2dot);
		char [] a=tm.toCharArray();
		char [] b=tm2dot.toCharArray();
		int delta=0;
		int i=a.length-1;
		int j=b.length-1;
		while(i>(a.length-pos-1))
		{
			if(a[i--]!=b[j--])
			{ 
				delta++;
				j--;
			}
			
		}
		text.setSpan(new StyleSpan(Typeface.BOLD), tm2dot.length()-pos-delta, tm2dot.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		        
			return text;
		
	}
@Override
public boolean onLongClick(View v) {
	// TODO Auto-generated method stub
	switch(v.getId())
	{
			//
			case R.id.In:
				if(EditCustomPad)
				{
					// Instantiates the drag shadow builder.
				    
				    // Starts the drag
				    ndrag=(Button) v;
				    Shadow dragshadow = new Shadow(v);
				    v.startDrag(null, dragshadow, v, 0);
				     break;
				}
				if(FlagLongOut==true && FlagLongIn==true)
	    		{
	     			int dur=(outdec-indec)>0?(outdec-indec):(indec-outdec);
	     			ViewTimecode(dur);
	     			FlagLongIn=FlagLongOut=false;
	    			break;
	    		}
			
			indec=curtm.TimecodeToFrames(curtm.strtime);
	     	curtm.end.prntwodot(curtm.end,curtm.positions);
	     	TIn.setText(Timecode2Dot(curtm.str,curtm.strtime,curtm.positions));			//
			correctWidth(TIn,300);// Подгоняем размер текста под размеры экрана
			FlagLongIn=!FlagLongIn;
			// send the tone to the "alarm" stream (classic beeps go there) with 50% volume
			ToneGenerator toneG1 = new ToneGenerator(AudioManager.STREAM_ALARM, 100);
			toneG1.startTone(ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD, 200); 
		
				break;
		case R.id.Out:
			if(EditCustomPad)
			{
			    // Instantiates the drag shadow builder.
			    
			    // Starts the drag
			    ndrag=(Button) v;
			      Shadow dragshadow = new Shadow(v);
			      v.startDrag(null, dragshadow, v, 0);
			     break;
			}
			if(FlagLongOut==true && FlagLongIn==true)
    		{
     			int dur=(outdec-indec)>0?(outdec-indec):(indec-outdec);
     			ViewTimecode(dur);
     			FlagLongIn=FlagLongOut=false;
    			break;
    		}
			outdec=curtm.TimecodeToFrames(curtm.strtime);
	     	curtm.end.prntwodot(curtm.end,curtm.positions);
	     	TOut.setText(Timecode2Dot(curtm.str,curtm.strtime,curtm.positions));			//
	     	correctWidth(TOut,300);// Подгоняем размер текста под размеры экрана
	     	FlagLongOut=!FlagLongOut;
	     	ToneGenerator toneG2 = new ToneGenerator(AudioManager.STREAM_ALARM, 100);
			toneG2.startTone(ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD, 200); 
			
	     	break;
	     	
	    default:	
			// Instantiates the drag shadow builder.
	
		    // Starts the drag
	    	if(v instanceof Button)
	    	{
	    				ndrag = v;
	    		((View)ndrag).setOnLongClickListener(maincl);
	    			
	    	    		//((View)ndrag).setOnTouchListener(maincl);
	    				//fl.setOnTouchListener(maincl);
	    	}
	    	if(v instanceof LinearLayout && ((LinearLayout)v).getChildCount()==0
	    			|| v instanceof FrameLayout && ((FrameLayout)v).getChildCount()==0
	    			|| v instanceof RelativeLayout && ((RelativeLayout)v).getChildCount()==0)
			{
	    		ndrag = v;
	    		((View)ndrag).setOnLongClickListener(maincl);
	    		
	    			 
	    		//fl.setOnTouchListener(maincl);
			}
	     	 Shadow dragshadow = new Shadow(v);
		      v.startDrag(null, dragshadow, v, 0);
		     break;

	}
		bwidth=v.getWidth();
	    bheight=v.getHeight();
	    dxsize=dysize=0;
		maxr=(float)Math.sqrt(bwidth*bwidth+bheight*bheight)/2;
	    bsel=true;
	    
	    SetLayer(v,R.drawable.btn_keyboard_key_pressed_border,
				R.id.lred,0,
				R.id.rred,0,
				R.id.tred,0,
				R.id.bred,0);
	    
	    if(v.getParent() instanceof LinearLayout)
	    {
		    	
		    	LinearLayout.LayoutParams param = (LinearLayout.LayoutParams)(v.getLayoutParams());
		    	v.setLayoutParams(param);
		    	
		 SetLayer(v,R.drawable.btn_keyboard_key_pressed_border,
				R.id.lred,(param.gravity==Gravity.LEFT)?255:0,
				R.id.rred,(param.gravity==Gravity.RIGHT)?255:0,
		   		R.id.tred,(param.gravity==Gravity.TOP)?255:0,
		   		R.id.bred,(param.gravity==Gravity.BOTTOM)?255:0);
		    	   
	   	 }
	    if(v.getParent() instanceof FrameLayout)
	    {
		    	
	    	FrameLayout.LayoutParams param = (FrameLayout.LayoutParams)(v.getLayoutParams());
		    	v.setLayoutParams(param);
		    	
		 SetLayer(v,R.drawable.btn_keyboard_key_pressed_border,
				R.id.lred,(param.gravity==Gravity.LEFT)?255:0,
				R.id.rred,(param.gravity==Gravity.RIGHT)?255:0,
		   		R.id.tred,(param.gravity==Gravity.TOP)?255:0,
		   		R.id.bred,(param.gravity==Gravity.BOTTOM)?255:0);
		    	   
	   	 }
	   
	    SetLayer(v,R.drawable.btn_keyboard_key_pressed_border,R.id.main_image,255);
	return true;
}


public class ButtonDragListener implements View.OnDragListener {

	
	ContextThemeWrapper	newContext;
	Drawable tmpd;
	
	@Override
	 public boolean onDrag(View v, DragEvent event) {
		
		switch (event.getAction()) {
        
			case DragEvent.ACTION_DRAG_STARTED:
				it=list.listIterator();
            	h.post(layer);
                    return true;
              
            case DragEvent.ACTION_DRAG_ENTERED:
            	
            break;
            
            case DragEvent.ACTION_DRAG_LOCATION:
            	
           	if(v==fl && EditCustomPad)
           		checkchild(fl,fl,event.getX()+fl.getLeft(),event.getY()+fl.getTop());
            if(v==lv && EditCustomPad)
                	lv.setBackgroundResource(R.drawable.layout);   
            else
             		lv.setBackground(null);
            return true;

            case DragEvent.ACTION_DRAG_EXITED:
                return true;
            case DragEvent.ACTION_DRAG_ENDED:
            	h.removeCallbacks(layer);
          	break;

            case DragEvent.ACTION_DROP:
            	
                if(EditCustomPad)
                {
                if(v==lv)
                	DragView(maincl,lv,ndrag);
                if(v==fl)
                {
                	DragView(lv,currentv,ndrag);
                		
                }	
                }
                 return true;
                
             	
        }
        return false;
    }
	

}
@SuppressWarnings("unchecked")
public Object checkchild(Object input,View root,float X,float Y)
{
	// Проверяем родительский элемент на попадание точки в его область
		if(input instanceof LinearLayout || input instanceof FrameLayout 
				|| input instanceof RelativeLayout)
	{
		
		float Left =GetParentX((View)input,root);
	    float Width = ((View)input).getWidth();
	    float Top = GetParentY((View)input,root);
	    float Height = ((View)input).getHeight();
	    
		if(X > Left && X < (Left + Width) && Y > Top && Y < (Top + Height))
		{

			if(!list.contains(input))
			{
				list.add(input);
				it=list.listIterator();
			}
		}
		else
		{
			if(list.contains(input))
			{
				setBackgroundView(currentv,false);
				list.remove(input);
			
			}
		}
	}
		// Проверяем наличие дочерних окон типа Layout
int countchild = 
		(input instanceof LinearLayout)?((LinearLayout)input).getChildCount():
		(input instanceof FrameLayout)?((FrameLayout)input).getChildCount():
		(input instanceof RelativeLayout)?((RelativeLayout)input).getChildCount():0;
		
		for(int i=0;i<countchild;i++)
		{
			if(input instanceof LinearLayout)
				checkchild(((LinearLayout)input).getChildAt(i),root,X,Y);
			if(input instanceof FrameLayout)
				checkchild(((FrameLayout)input).getChildAt(i),root,X,Y);
			if(input instanceof RelativeLayout)
				checkchild(((RelativeLayout)input).getChildAt(i),root,X,Y);
		}
		
return input;
		}	
Runnable layer= new Runnable(){

	@Override
	public void run() {
		// TODO Auto-generated method stub
	
	if(!list.isEmpty())
{
		if(currentv!=null)
		{
			setBackgroundView(currentv,false);
		//	((View)currentv).setEnabled(true);
		}
		if(it.hasNext())
			currentv=it.next();
		else
			while(it.hasPrevious())
				it.previous();
		if(it.hasNext())
			currentv=it.next();			
		
		if(currentv!=null)
				setBackgroundView(currentv,true);
}

	h.postDelayed(layer, 2000);		
	}
};
public void setBackgroundView(Object o,boolean EnableBackground)
{
	if(EnableBackground)
	{
	if(o instanceof LinearLayout)
		if(((LinearLayout)o).getLayoutDirection()==View.LAYOUT_DIRECTION_LTR)
		{
		  SetLayer(o,R.drawable.linearl_v,R.id.lred,0,R.id.rred,0,R.id.tred,0,R.id.bred,0);
		}
		else
		{
			SetLayer(o,R.drawable.linearl_h,R.id.lred,0,R.id.rred,0,R.id.tred,0,R.id.bred,0);
		}
		
	if(o instanceof FrameLayout)
	{
			 SetLayer(o,R.drawable.framel,R.id.lred,0,R.id.rred,0,R.id.tred,0,R.id.bred,0);
			
	}
	if(o instanceof RelativeLayout)
	{
		  SetLayer(o,R.drawable.relativel,R.id.lred,0,R.id.rred,0,R.id.tred,0,R.id.bred,0);
	}
	}
	else
		((View)o).setBackground(null);
}//

// Получем Х координату относительно root окна.
private int GetParentX(Object o, View root) {

	if (o==root)
		return ((View)o).getLeft();
else
	return ((View)o).getLeft()+GetParentX(((ViewParent) o).getParent(),root); 

}
private int GetParentY(Object o, View root) {

	if (o==root)
			return ((View)o).getTop();
	else
		return ((View)o).getTop()+GetParentY(((ViewParent) o).getParent(),root); 
		
}
public boolean DragView(Object srcview,Object dstview,Object dragobject)
{
	ViewParent parent=null;
	
	if(dragobject!=null && srcview!=null && dstview!=null)
	{
	
		if(dragobject instanceof Button)
		{
			
			Button	btn=new Button(((View) dragobject).getContext());
			btn.setBackground(((Button)ndrag).getBackground());
		   	btn.setText(((Button)ndrag).getText());
		   	btn.setLayoutParams(((Button) dragobject).getLayoutParams());
		    btn.setOnLongClickListener(maincl);
		    btn.setOnTouchListener(maincl);
		    
		if(dstview instanceof LinearLayout)
		{
			((LinearLayout)dstview).addView(btn);
		}
		if(dstview instanceof FrameLayout)
			((FrameLayout)dstview).addView(btn);
		if(dstview instanceof RelativeLayout)
			((RelativeLayout)dstview).addView(btn);
		if(dstview instanceof LinearLayout || dstview instanceof FrameLayout || dstview instanceof RelativeLayout )
		{	
			parent=((Button)dragobject).getParent();
			//if(srcview!=lv) 
			((Button)dragobject).setVisibility(View.GONE);
		}
		if(parent instanceof LinearLayout )
		{
			View tmp = ((LinearLayout)parent).findViewById(((Button)dragobject).getId());
				((LinearLayout)parent).removeView(tmp);
			if(((LinearLayout)parent).getChildCount()==0)
			{
				((LinearLayout)parent).setOnLongClickListener(maincl);
				((LinearLayout)parent).setOnTouchListener(maincl);
				
				if(((LinearLayout)parent).getLayoutDirection()==View.LAYOUT_DIRECTION_LTR)
					((LinearLayout)parent).setBackgroundResource(R.drawable.linearl_v);
				if(((LinearLayout)parent).getLayoutDirection()==View.LAYOUT_DIRECTION_RTL)
					((LinearLayout)parent).setBackgroundResource(R.drawable.linearl_h);
			}
		}
		if(parent instanceof FrameLayout )
		{
			View tmp = ((FrameLayout)parent).findViewById(((Button)dragobject).getId());
			
				((FrameLayout)parent).removeView(tmp);
			if(((FrameLayout)parent).getChildCount()==0)
			{
				((FrameLayout)parent).setOnLongClickListener(maincl);
				((FrameLayout)parent).setOnTouchListener(maincl);
			}
			((FrameLayout)parent).setBackgroundResource(R.drawable.framel);
		}
		if(parent instanceof RelativeLayout )
		{
			View tmp = ((RelativeLayout)parent).findViewById(((Button)dragobject).getId());
				((RelativeLayout)parent).removeView(tmp);
			if(((RelativeLayout)parent).getChildCount()==0)
			{
				((RelativeLayout)parent).setOnLongClickListener(maincl);
				((RelativeLayout)parent).setOnTouchListener(maincl);
			}
			((RelativeLayout)parent).setBackgroundResource(R.drawable.relativel);
		}
		return true;
		}
				if(dragobject instanceof LinearLayout && ((LinearLayout)dragobject).getChildCount()==0)
			{
				LinearLayout linearLayout = new LinearLayout(this);
				linearLayout.setLayoutParams(((LinearLayout)dragobject).getLayoutParams());
				((LinearLayout)dstview).addView(linearLayout);
				if(srcview!=lv) 
				{
					((LinearLayout)dragobject).setVisibility(View.GONE);
					View tmp = fl.findViewById(((LinearLayout)dragobject).getId());
					fl.removeView(tmp);
				}
				return true;
			}
			if(dragobject instanceof FrameLayout && ((FrameLayout)dragobject).getChildCount()==0)
			{
				FrameLayout frameLayout = new FrameLayout(this);
				frameLayout.setLayoutParams(((FrameLayout)dragobject).getLayoutParams());
				((LinearLayout)dstview).addView(frameLayout);
				if(srcview!=lv)
				{
				((FrameLayout)dragobject).setVisibility(View.GONE);
				View tmp = fl.findViewById(((FrameLayout)dragobject).getId());
				fl.removeView(tmp);
				}
				return true;
			}
			if(dragobject instanceof RelativeLayout && ((RelativeLayout)dragobject).getChildCount()==0)
			{
				RelativeLayout relativeLayout = new RelativeLayout(this);
				relativeLayout.setLayoutParams(((RelativeLayout)dragobject).getLayoutParams());
				((LinearLayout)dstview).addView(relativeLayout);
				if(srcview!=lv) 
				{
				((RelativeLayout)dragobject).setVisibility(View.GONE);
				View tmp = fl.findViewById(((FrameLayout)dragobject).getId());
				fl.removeView(tmp);
				}
				return true;
			}
	
	}
	
	return false;
}
@Override
public boolean onTouch(View v, MotionEvent event) {
	// TODO Auto-generated method stub
	// Событие
	int actionMask = event.getActionMasked();
	float w=v.getWidth();
	float h=v.getHeight();

	// Координаты касания второго касания
	int deltax=(int)(w/5);
	int deltay=(int)(h/5);

	
	///float oy=((View)ndrag).getTop();
	// Число Касаний
	//int pointCount = event.getPointerCount();
	switch(actionMask)
	{
	case MotionEvent.ACTION_DOWN:
		
		xff=event.getX(0);
		yff=event.getY(0);
			break;
	case MotionEvent.ACTION_UP:
		
		if(event.getPointerCount()==1 && bsel )
		{
	int tGravity=0;
	if(l)
		tGravity = tGravity | Gravity.START;
	if(r)
		tGravity = tGravity | Gravity.END;
	if(t)
		tGravity = tGravity | Gravity.TOP;
	if(b)
		tGravity = tGravity | Gravity.BOTTOM;
	

	if(v.getParent() instanceof LinearLayout)
			{
				LinearLayout.LayoutParams params=(LinearLayout.LayoutParams)(v.getLayoutParams());
				params.gravity=tGravity;
				params.width=bwidth+dxsize;
			    params.height=bheight+dysize;
				
				if(l && r)
					params.width=LayoutParams.MATCH_PARENT;
				if(t && b)
					params.height=LayoutParams.MATCH_PARENT;
				v.setLayoutParams(params);
			}
	if(v.getParent() instanceof FrameLayout)
			{
				FrameLayout.LayoutParams params=(FrameLayout.LayoutParams)(v.getLayoutParams());
				params.gravity=tGravity;
				params.width=bwidth+dxsize;
			    params.height=bheight+dysize;
				
				if(l && r)
					params.width=LayoutParams.MATCH_PARENT;
				if(t && b)
					params.height=LayoutParams.MATCH_PARENT;
		
				v.setLayoutParams(params);
			}
	if(v.getParent() instanceof RelativeLayout)
	{
		RelativeLayout.LayoutParams params=(RelativeLayout.LayoutParams)(v.getLayoutParams());
		params.width=bwidth+dxsize;
	    params.height=bheight+dysize;
	if(l && r)
			params.width=LayoutParams.MATCH_PARENT;
		if(t && b)
			params.height=LayoutParams.MATCH_PARENT;

		v.setLayoutParams(params);
	}
	v.setBackgroundResource(android.R.drawable.btn_default);
	bsel=false;
	//btn.setOnTouchListener(null);
		}
		
		break;
	// Последующие нажатия
	case MotionEvent.ACTION_POINTER_DOWN:
		
			float x=event.getX(1);
			float y=event.getY(1);
			xsf=x;
			ysf=y;
			float modwx=((x-w)>0)?(x-w):(w-x);
			float modhy=((y-h)>0)?(y-w):(w-y);
			float modx=(x>0)?x:-x;
			float mody=(y>0)?y:-y;
			
			if(modx<deltax && y>deltay && y<(h-deltay))
			{
			l=!l;
			SetLayer(v,R.drawable.btn_keyboard_key_pressed_border,R.id.lred,((l)?255:0));
			}
			if(modwx<deltax && y>deltay && y<(h-deltay))
			{
			r=!r;
			SetLayer(v,R.drawable.btn_keyboard_key_pressed_border,R.id.rred,((r)?255:0));
			}
			if(mody<deltay && x>deltax && x<(w-deltax))
			{
			t=!t;
			SetLayer(v,R.drawable.btn_keyboard_key_pressed_border,R.id.tred,((t)?255:0));
				
			}
			if(modhy<deltay && x>deltax && x<(w-deltax))
			{
			b=!b;
			SetLayer(v,R.drawable.btn_keyboard_key_pressed_border,R.id.bred,((b)?255:0));
			}
	//		tv.setText("X="+String.valueOf(x)+" Y="+String.valueOf(y));
			if(y>(yff-deltay) && y<(yff+deltay) && (x>(xff+deltax) || x<(xff-deltax)))
				dxsize+=(x<xff)?-5:5;
									
			if(x>(xff-deltax) && x<(xff+deltax) && (y>(yff+deltay) || y<(yff-deltay)))
				dysize+=(y<yff)?-5:5;

			ViewGroup.LayoutParams params = v.getLayoutParams();
			
		    params.width=bwidth+dxsize;
		    params.height=bheight+dysize;
		    
		    v.setLayoutParams(params);
			
		    cornerdrag=
					// Правый нижний угол
					xsf>(w-deltax) && xsf<(w+deltax) && ysf>(h-deltay) && ysf<(h+deltay) ||
					// Левый нижний угол
					xsf>-deltax && xsf<deltax && ysf>(h-deltay) && ysf<(h+deltay) ||
					// Правый верхний угол
					xsf>(w-deltax) && xsf<(w+deltax) && ysf>(-deltay) && ysf<(deltay) ||
					// Левый верхний Угол
					xsf>(-deltax) && xsf<(deltax) && ysf>(-deltay) && ysf<(+deltay);

		   
		 // 	tv.setText("X="+String.valueOf(x)+" Y="+String.valueOf(y)+ "\n fX="+String.valueOf(xff)+" fY="+String.valueOf(yff));
						
		break;
	// Последующие отпускания	
	case  MotionEvent.ACTION_POINTER_UP:
		cornerdrag=false;
		break;
	// Перемещение
	case MotionEvent.ACTION_MOVE:

				if(cornerdrag && event.getPointerCount()==2)
			{
					float mx=event.getX(1);
					float my=event.getY(1);
					
					float xq=(xff<mx)?(xff-mx)*(xff-mx):(mx-xff)*(mx-xff);
					float yq=(yff<my)?(yff-my)*(yff-my):(my-yff)*(my-yff);
					float dr=(float) Math.sqrt(xq+yq);
		
				if(v.getParent() instanceof LinearLayout)
			    {
				    	
				    	LinearLayout.LayoutParams param = (LinearLayout.LayoutParams)(v.getLayoutParams());
				    	param.weight =dr/maxr;
				    	v.setLayoutParams(param);
			    	
			   	v.refreshDrawableState(); // This is to explicit force the refresh.
			     }
					
			}
			  	
		break;
		
	}
	return false;
}

boolean SetLayer(Object o,int AllLayer_drawable,int ...layer_id_alpha)
{
 
	if(o==null || AllLayer_drawable==0 || (layer_id_alpha.length)%2!=0 || (layer_id_alpha.length)==0)
		return false;
	LayerDrawable ll = ((LayerDrawable)getResources().getDrawable(AllLayer_drawable));
	if(ll==null)
		return false;
	for(int i=0;i<layer_id_alpha.length;i+=2)
	{
		Drawable dl=ll.findDrawableByLayerId(layer_id_alpha[i]);
		if(dl==null)
			return false;
		dl.setAlpha(layer_id_alpha[i+1]);
	}
	((View)o).setBackground(ll);
	return true;
}
}
